<?php
/**
 * 系统配置
 * User: lxl
 */

namespace App\Service\Core\Sys\Config;

use App\Model\Core\Sys\SysConfigModel;
use App\Service\ParamsService;
use App\Service\Core\CoreBaseService;
use App\Traits\SingleInstanceTrait;

class SysConfigService extends CoreBaseService
{
    use SingleInstanceTrait;

    private SysConfigModel $SysConfigModel;

    public function __construct()
    {
        $this->SysConfigModel = SysConfigModel::getInstance();
    }

    /**
     * 设置配置
     * @param $config_item
     * @param $config_val
     * @param $operate_id
     * @param $operate_by
     * @return array
     */
    public function setConfig($config_item, $config_val, $operate_id, $operate_by): array
    {
        $config_item = trim($config_item);
        $res = $this->SysConfigModel->setConfig($config_item, $config_val, $operate_by);
        if (!$res) {
            return alert_info(1, '设置失败');
        }
        $config_list = ParamsService::$config_item_list;
        $this->addLog('系统设置', ' 设置【' . $config_list[$config_item] . '】', $operate_id, $operate_by);
        return alert_info(0, '设置成功');
    }

    /**
     * 获取配置
     * @param $config_item
     * @param $default
     * @return mixed|null
     */
    public function getConfig($config_item, $default = null): mixed
    {
        $info = $this->SysConfigModel->getConfig($config_item);
        if (empty($info) || $info['config_val'] === '') {
            return $default;
        }
        return $info['config_val'];
    }

    /**
     * 获取配置项列表
     * @return array
     */
    public function getList(): array
    {
        $dict_item_list = ParamsService::$dict_item_list;
        $config_list = [];
        foreach ($dict_item_list as $key => $item) {
            $config_val = $this->getConfig($key);
            $config_list[] = [
                'config_item' => $key,
                'config_name' => $item['name'],
                'config_val' => $config_val,
                'ext_field_name' => $item['ext_field_name'],
                'ext_field_type' => $item['ext_field_type'],
            ];
        }
        return $config_list;
    }
}
